<?php

namespace App\Http\Controllers\Admin\ExportReport;

use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use PhpOffice\PhpWord\IOFactory;
use Storage;
use App\Http\Controllers\Admin\ItemDataController;
use App\Http\Controllers\Admin\ExportReport\ExportReportPublicController;

class ExportReportShanDongZiBoQianHengController extends Controller
{
    protected $sourceDir = './storage/ExcelTemplate/ShanDongZiBoQianHeng/';
    private $disk=null;
    private $storeFile='';

    /* 导出Word 检测报告*/
    public function export(Request $request) {
        ini_set('pcre.backtrack_limit', 999999999);
        $contract_id = (int)$request->id; //批次 id
        //查询当前批次的信息
        $data_batch = DB::table('a_contract as a')
            ->leftJoin('a_status_time as b','a.id','=','b.contract_id')
            ->where('a.id',$contract_id)
            ->first();
        // dd($data_batch);
        $batchNum = $data_batch->batchNum;
        $storeFile = $this->storeFile = 'reports/'.$batchNum.'.docx';
        //$storeFile = "reports/{$batchNum}/{$batchNum}.docx";
        $disk = $this->disk = Storage::disk('public');
        $new = request('new',0);
        if($disk->exists($storeFile) && $new == 0){
            $lastModified = $disk->lastModified($storeFile);
            // dd($lastModified);
            if ($lastModified > strtotime($data_batch->report_end)) {
               return $disk->download($storeFile);
            }
        }

        /**
         * 封面模板数据*************************************************
         */
        $filename = "检测报告模板.docx";
        $temp_file = $this->sourceDir.$filename; //考虑到兼容Linux，斜杠用“/”
        if(!file_exists($temp_file)) {
            return '封面模板文件不存在';
        }

        //加载模板类
        $template = new \PhpOffice\PhpWord\TemplateProcessor($temp_file);
        //模板中单独参数
        $values = [];

        $setting1 = DB::table('setting')->find(1);
        $report_num_pre = $setting1->report_num_pre; //报告编号前缀
        $company_name = $setting1->name_rep; //获取检测公司名称

        //获取voltage
        $sql = "SELECT DISTINCT voltage FROM a_contract_gaiyao WHERE contract_id = ".$contract_id;
        $voltage_array = DB::select($sql);
        $vstr = '';
        if($voltage_array) {
            foreach ($voltage_array as $key => $val) {
                if ($val->voltage != '/') {
                    $vstr .= trim($val->voltage,'kV') . '/';
                }
            }
            $vstr = rtrim($vstr,'/');
        }
        // //检测性质
        // $image = DB::table('a_test_kind')->where('name',$data_batch->test_kind)->value('image');
        // $template->setImageValue('test_kind', ["path" => trim($value,'/'), "height" => 100]);
        //配置参数
        $values = [
            // 'batchNum' => $report_num_pre . $data_batch->batchNum,
            'batchNum' => $data_batch->batchNum,
            'voltage' => $vstr.'kV',
            'entrusted_company' => $data_batch->entrusted_company,
            'contacts' => $data_batch->client_contact,
            'telephone' => $data_batch->client_tel,
            'address' => $data_batch->client_addr,
            'test_type' => $data_batch->test_type,
            'report_end' => date('Y年m月d日',strtotime($data_batch->created_at)),
            'year'=>date('Y',strtotime($data_batch->created_at)),
            'month'=>date('m',strtotime($data_batch->created_at)),
            'day'=>date('d',strtotime($data_batch->created_at)),
            'test_name' => $data_batch->test_name,
        ];

        $template->setValues($values);
        $values = [];

        /**
         * 目录模板数据********************************************************
         */
        //获取item_names
        $sql = "SELECT DISTINCT item_names FROM a_contract_gaiyao WHERE contract_id = ".$contract_id;
        $item_names_array = DB::select($sql);
        $item_names_str = '';
        $item_names_arr = [];
        if($item_names_array) {
            foreach ($item_names_array as $key => $val) {
                if ($val->item_names != '/') {
                    $newarr = explode('，',$val->item_names);
                    $item_names_arr = array_merge($item_names_arr,$newarr);
                }
            }
            $item_names_str = implode(',',array_unique($item_names_arr));
        }

        //温湿度
        $mhum = '';
        $mtemp = '';
        $temp_hum_sqs = "select max(temp) as maxtemp,min(temp) as mintemp,max(hum) as maxhum ,min(hum) as minhum from a_item_data where temp != '' and hum !='' and contract_id= ".$contract_id;
        $temp_hum_data = DB::select($temp_hum_sqs);
        if($temp_hum_data){
            $temp_hum_data_min = $temp_hum_data[0]->mintemp; //最小温度
            $temp_hum_data_max = $temp_hum_data[0]->maxtemp; //最大温度
            $mtemp = $temp_hum_data_min == $temp_hum_data_max ? $temp_hum_data_max : $temp_hum_data_min.' ~ '.$temp_hum_data_max;
            $mhum_min = $temp_hum_data[0]->minhum; //最小湿度
            $mhum_max = $temp_hum_data[0]->maxhum; //最大湿度
            $mhum = $mhum_min == $mhum_max ? $mhum_max : $mhum_min.' ~ '.$mhum_max;
        }
        //检测仪器
        $dev_data = DB::table('a_item_data as i')->leftjoin('a_station as s','i.station_ids','=','s.id')->select('s.*')->where('contract_id',$contract_id)->where('station_ids','!=','')->get();
        $dev_array = [];
        $dev_data = DB::table('a_item_data')->select('id','station_ids')->where('contract_id',$contract_id)->where('station_ids','!=','')->get();
        if($dev_data) {
            $y=0;
            foreach ($dev_data as $ke => $va) {
                $new_arr = explode(',',$va->station_ids);
                foreach($new_arr as $yv){
                    $dev_result = DB::table('a_station')->select('name','spec','dev_num','trace_exp_date')->where('id',$yv)->first();
                    if ($dev_result) {
                        $dev_array[$y]['dev_name'] = $dev_result->name;
                        $dev_array[$y]['dev_spec'] = $dev_result->spec;
                        $dev_array[$y]['dev_num'] = $dev_result->dev_num;
                        $dev_array[$y]['dev_exp'] = $dev_result->trace_exp_date?:'/';
                        $y++;
                    }
                }
            }
            $dev_array = $this->array_duplicate($dev_array);
        }

        //检测依据
        $standards = '';
        $stand_sql = "SELECT DISTINCT std_num FROM a_contract_gaiyao WHERE contract_id = ".$contract_id;
        $stand_array = DB::select($stand_sql);
        if($stand_array){
            foreach($stand_array as $ky=>$vy){
                $stand_name = DB::table('a_standard')->where('num',$vy->std_num)->pluck('name');
                $standards .= "<w:ind/>".$vy->std_num."《{$stand_name[0]}》;<w:br/>";
            }
        }
        $standards = rtrim($standards,'<w:br/>');

        //追加单独参数
        $values['reportList'] = '';
        // $values['item_names'] = [$item_names_str,28]; 
        $values['all_test_items'] = $item_names_str; 
        $values['temp'] = $mtemp;
        $values['humi'] = $mhum;
        $values['standards'] = $standards;
        // $values['test_items'] = $item_names_str;

        //循环写入
        $count = count($dev_array);
        $template->cloneRow('dev_name',$count);
        foreach($dev_array as $key=>$val){
            $xu = $key+1;
            foreach($val as $k=>$v){
                $template->setValue($k.'#'.$xu,$v);
            }
        }

        /**
         * 结论汇总模板数据*****************************************************
         */
        $testdate_start = DB::table('a_sample_info as B')->leftJoin('a_contract_gaiyao as A', 'A.id', '=', 'B.contract_gaiyao_id')->where('B.contract_id', $contract_id)->min('test_time');
        //检验日期结束时间
        $testdate_end = DB::table('a_sample_info as B')->leftJoin('a_contract_gaiyao as A', 'A.id', '=', 'B.contract_gaiyao_id')->where('B.contract_id', $contract_id)->max('test_time');
        //合格样品
        $hege = DB::table('a_sample_info as B')->leftJoin('a_contract_gaiyao as A', 'A.id', '=', 'B.contract_gaiyao_id')->where('B.contract_id', $contract_id)->where('B.res',1)->get();
        //不合格样品
        $unqugqj = DB::table('a_sample_info as B')->leftJoin('a_contract_gaiyao as A', 'A.id', '=', 'B.contract_gaiyao_id')->select('A.*','B.photo','B.non_photo','B.id as sid')->where('B.contract_id', $contract_id)->where('B.res',2)->get();
        $buhege_array = [];
        $bfh_details = '';
        if($unqugqj){
            foreach($unqugqj as $key=>$val){
                $sql = "SELECT A.id,B.`name`,D.tool_name,D.unit FROM a_item_data AS A 
                    LEFT JOIN a_testitem AS B ON A.item_id = B.id
                    LEFT JOIN a_contract_gaiyao AS D ON A.contract_gaiyao_id = D.id
                    LEFT JOIN a_std_tool_item_rel AS E ON D.std_id = E.std_id
                    AND D.tool_id = E.tool_id
                    AND A.item_id = E.testitem_id
                    WHERE A.res = 0 and A.sample_info_id = :sample_info_id ";
                $item_data = DB::select($sql,['sample_info_id'=>$val->sid]);
                foreach($item_data as $k=>$v){
                    $buhege_array[$v->tool_name][] = $v;
                }
            }
            if($buhege_array) {
                $bfh_arr = [];
                $bfh_details = '其中';
                foreach ($buhege_array as $kk => $vv) {
                    //$bfh_details .= $kk . '不符合的项目' . count($vv) . '项：';
                    foreach ($vv as $k => $v) {
                        $bfh_arr[] = $v->name;
                        //$bfh_details .= $v->name;
                        //$bfh_details .= $k == count($vv) - 1 ? '；' : '、';
                    }
                    $bfh_arr = array_unique($bfh_arr);
                    $bfh_details .= $kk . '不符合的项目' . count($bfh_arr) . '项：';
                    foreach($bfh_arr as $key=>$val){
                        $bfh_details .= $val;
                        $bfh_details .= $key == count($bfh_arr) - 1 ? '；' : '、';
                    }
                }
            }else{
                $bfh_details = '';
            }
        }

        //样品编号
        //$gqj_code_str = $this->getBarCodes($contract_id);
        $gqj_code_str = $this->NewgetBarCodes($contract_id);
        //追加单独参数
        $values['gqj_number'] = $gqj_code_str;
        $values['yp_date'] = date('Y年m月d日',strtotime($data_batch->created_at));
        $values['test_start_date'] = date('Y年m月d日',strtotime($testdate_start));
        $values['test_end_date'] = date('Y年m月d日',strtotime($testdate_end));
        $values['hg_number'] = count($hege);
        $values['bfh_number'] = count($unqugqj);
        $values['bfh_details'] = $bfh_details;


        //检测结果汇总表
        $huizong = DB::table('a_contract_gaiyao')->select('id','tool_name','count','bar_codes')->where('contract_id',$contract_id)->get();
        $replacements = [];
        if($huizong) {
            foreach ($huizong as $key => $val) {
                $replacements[$key]['hzNo'] = $key+1;
                $replacements[$key]['hzToolName'] = $val->tool_name;
                $replacements[$key]['hzTotal'] = $val->count;
                $replacements[$key]['hzHgTotal'] = DB::table('a_sample_info')->where('contract_gaiyao_id', $val->id)->where('res', 1)->count();
                $hzUnTotal = DB::table('a_sample_info')->where('contract_gaiyao_id', $val->id)->where('res', 2)->get();
                $replacements[$key]['hzUnTotal'] = $hzUnTotal->count();
                $replacements[$key]['unSeason'] = $this->getUnSeason($hzUnTotal);
            }
        }
        $count = count($replacements);
        $template->cloneRow('hzNo',$count);
        foreach($replacements as $key=>$val){
            $xu = $key+1;
            foreach($val as $k=>$v){
                $template->setValue($k.'#'.$xu,$v);
            }
        }
        $gys = DB::table('a_contract_gaiyao')->where('contract_id',$contract_id)->orderBy('id')->get();
        $samples2 = $result = [];

        foreach($gys as $key=>$val){
            // dd($val);
            $samples = DB::table('a_sample_info as a')
                ->leftJoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')
                ->where('a.contract_gaiyao_id',$val->id)
                ->where('a.res','<>',0)
                ->select('a.id as sample_info_id','a.bar_code','a.guige_xinghao','a.sample_status','a.manufacturer','a.test_time','a.next_time','a.res','a.contract_gaiyao_id','a.non_photo','a.self_num','b.item_names','b.voltage','b.std_num','b.unit','b.std_id','b.item_ids','b.tool_id','b.class_id','b.vol_id','b.tool_name')
                ->get()->toArray();
            // dd($samples,$val->count);
            if (count($samples) != $val->count) {
                return '有样品未出结果！';
            }
            foreach ($samples as $sample) {
                $samples2[$val->tool_name][$sample->res][] = $sample;
            }

            // dd($samples2);
            foreach ($samples2 as $tool_name => $item) {
                $res = [1,2]; 
                foreach ($res as $resV) {
                    $itemV = data_get($item,$resV,'');
                    if ($itemV) {
                        $data = &$result[$tool_name][$resV];
                        $remarks = $this->getRemark2($itemV);
                        $data['tool_name'] = $tool_name;
                        //$data['bar_code'] = $this->getBarCodes2(array_column($itemV,'bar_code'));//(不)合格样品的条码排序
                        $data['bar_code'] = $this->NewgetBarCodes2(array_column($itemV,'contract_gaiyao_id'),$resV);//(不)合格样品的条码排序
                        $data['guigexinghao'] = $this->getUnique(array_column($itemV,'guige_xinghao'));
                        $data['sample_status'] = $this->getUnique(array_column($itemV,'sample_status'));
                        $data['count'] = count($itemV);
                        $data['unit'] = $this->getUnique(array_column($itemV,'unit'));
                        $data['manufacturer'] = $this->getUnique(array_column($itemV,'manufacturer'));
                        $data['test_time'] = $this->getUnique(array_map(function ($item)
                        {
                            return $item ? date('Y年m月d日',strtotime($item)) : $item;
                        },array_column($itemV,'test_time')));
                        $data['cycle'] = $this->getCycle2($itemV);
                        $data['next_time'] = $this->getUnique(array_map(function ($item)
                        {
                            return $item ? date('Y年m月d日',strtotime($item)) : $item;
                        },array_column($itemV,'next_time')));
                        $data['item_names'] = $this->getUnique(array_column($itemV,'item_names'));
                        $data['jishu_yaoqiu'] = $this->getYaoqius2($itemV);
                        list($data['temp'],$data['humi'],$data['pressure']) = $this->getEnv2($itemV);
                        switch ($resV) {
                            case 1:
                                break;
                            case 2:
                                $ssid = array_column($itemV,'sample_info_id');
                                $item_names = DB::table('a_item_data as a')
                                    ->leftjoin('a_testitem as b','a.item_id','=','b.id')
                                    ->leftjoin('a_sample_info as s','a.sample_info_id','=','s.id')
                                    ->select('b.name','s.self_num')
                                    ->whereIn('a.sample_info_id',$ssid)
                                    ->where('a.res',0)
                                    ->get()->toArray();
                                $unSeason = '外观检查不符合标准要求';
                                if($item_names){
                                    $unSeason = '';
                                    foreach ($item_names as $item => $count) {
                                        if($count->name == '外观检查'){
                                            $unSeason .= "{$count->self_num}".'、';
                                        }
                                    }
                                    $unSeason = rtrim($unSeason,'、');
                                    $unSeason .= ' 外观检查不符合标准要求;';
                                }
                                $data['wai_res'] = $unSeason;//implode('、',array_column($itemV,'bar_code')).'外观检查不符合标准要求';
                                $suggest = $data['test_after'] = $remarks;
                                $data['suggest'] = $suggest ? $suggest.'，建议停用' : '建议停用';
                                $data['non_photos'] = $this->getNonPhotos($itemV);
                                break;
                            default:
                                break;
                        }
                        if($resV==2){
                            $data['sample_status'] = '不符合标准要求';
                            $ssid = array_column($itemV,'sample_info_id');
                            $item_names = DB::table('a_item_data as a')
                                ->leftjoin('a_testitem as b','a.item_id','=','b.id')
                                ->whereIn('a.sample_info_id',$ssid)
                                ->where('a.res',0)
                                ->pluck('b.name')->toArray();
                            $unSeason = '';
                            if($item_names){
                                foreach ($item_names as $item => $count) {
                                    $unSeason .= "{$count}不合格".';';
                                }
                                $data['sample_status'] = $unSeason;
                            }
                        }
                        $data['sample_info_ids'] = array_column($itemV,'sample_info_id');
                        $data['std_num'] = $this->getUnique(array_column($itemV,'std_num'));
                    }
                }
            }
        }

        //获取试验数据start
            foreach ($result as $tool_name => &$item) {
                foreach ($item as $res => &$resV) {
                    // dd($resV);
                    //整理试验数据
                    $resV['test_data'] = $this->getTestDataVals2($resV);
                    unset($resV['sample_info_ids']);                
                }
            }
            unset($item,$resV);
        //获取试验数据end
        /*=========== 目录序列 start 必须先设置目录才可以，不然不能用 ============*/
            /*标准 start*/
            $std_rows = substr_count($standards,'<w:br/>');
            $std_rows += 1;
            /*标准 end*/
            /*检测设备-检测项目 start*/
                $dev_per_row_limit = [
                    'dev_name'=>16,
                    'dev_spec'=>11,
                    'dev_num'=>10,
                ];
                $per_page_limit = 21;//如果一页占用21行
                $dev_page_limit = [10-$std_rows,$per_page_limit]; //【起始页最大占用行数，整页最大占用行数】 
                list($dev_rows,$dev_pages,$last_page_left_rows) = $this->getRowLimit($dev_array,$dev_per_row_limit,$dev_page_limit);
                // dd($dev_rows,$dev_pages,$last_page_left_rows,$dev_page_limit);
                $pNo = 2; //初始化pageNo
                $pNo += $dev_pages-1;
                $pNo += $last_page_left_rows == 0 ? 1 : 0; //如果没有剩余行则换页了
                $pNo_item = $pNo;
                $last_page_left_rows -= 1; //5.检测项目 标题占一行 减去标题行
                $test_items_rows = $this->getStrRows($item_names_str.'0000',60); //因为第一行有首行缩进，所以这里补0做计算
                $last_page_left_rows -= $test_items_rows; //计算减去检测项目占用的行数后剩余行，如果是负数说明跨页了
                if ($last_page_left_rows < 0) {
                    $more_rows = abs($last_page_left_rows);
                    $pNo += ceil($more_rows/$per_page_limit); //计算跨页的页数 添加页数
                    $last_page_left_rows = $more_rows%$per_page_limit; //计算最后一页减去检测项目占用行后剩余行
                }
                $pNo += $last_page_left_rows == 0 ? 1 : 0; //如果没有剩余行则换页了
                // dd($pNo,$last_page_left_rows);
            /*检测设备-检测项目 end*/
            /*检测报告开始页码 start*/
                $pNo_report = $pNo;
                $pNo += 1; //换页符 进入下一页
                $gqj_number_rows = $this->getStrRows($gqj_code_str,22);
                $bfh_details_rows = $this->getStrRows($bfh_details,49);
                if ($gqj_number_rows + $bfh_details_rows > 8) {
                    $pNo += 1;  //如果超出页码可承受范围，页码+1
                }
            /*检测报告结束页码 end*/
            /*检测结果汇总表 开始页码 start*/
                $pNo += 1; //换页符 进入下一页
                if (array_sum(array_column($gys->toArray(),'count')) > 16) {  //如果合同概要数量大于16（一页只能放下16个），换页
                    $pNo += 1; //目前只考虑了换一页的情况
                }
            /*检测结果汇总表 结束页码 end*/
            /*概要信息 开始页码 start*/
                $pNo += 1; //换页符 进入下一页
                $ml = [];
                // dd($result);
                $tools = array_values($result);
                // dd($tools);
                foreach ($tools as $ka => $toolVa) {
                    $toolVa0 = current($toolVa);
                    $ml[$ka]['muluno'] = $pNo;
                    $ml[$ka]['muluname'] = ($ka+1) . '.' . $toolVa0['tool_name'];
                    foreach ($toolVa as $res => $va) {
                        $va = (object)$va;
                        // dd($va);
                        $totalRows = 0;
                        $bar_codes_rows = count(explode('，',$va->bar_code));
                        $totalRows += $bar_codes_rows > 2 ? $bar_codes_rows : 2;
                        $va->item_names = implode('，',array_unique(explode('，',$va->item_names)));
                        $item_names_rows = $this->getStrRows($va->item_names.'0000',28); //用0占用首行缩进位置
                        $totalRows += $item_names_rows > 2 ? $item_names_rows : 2;
                        // dd($item_names_rows);
                        $yaoqiu_rows = $this->getStrRows(data_get($va,'jishu_yaoqiu','/').'0000',61);
                        $totalRows += $yaoqiu_rows > 2 ? $yaoqiu_rows : 2;
                        $input_val_str = data_get($va,'test_data','/');
                        $input_val_rows = count(explode('<w:br/>',$input_val_str));
                        $test_after_str = data_get($va,'test_after','/');
                        $test_after_rows = $this->getStrRows($test_after_str,14) + 2; //加上标题占的2行
                        $test_after_rows = $test_after_rows > 4 ? $test_after_rows : 4; 
                        $test_data_rows = $input_val_rows > $test_after_rows ? $input_val_rows : $test_after_rows;
                        $totalRows += $test_data_rows > 3 ? $test_data_rows : 3;
                        if ($totalRows > 17) {
                            $pNo += 1; //这里只计算了换一页
                        }
                        if ($res == 2) { //+不合格照片的页数
                            $pNo += $va->count;
                        }
                        $pNo += 1;//换页符 进入下一页
                    }
                }
                // dd($ml);
                // dd($ml);
                $template->cloneBlock('mulu', 0, true, false, $ml);
                // dd($gys);
            /*概要信息 结束页码 end*/
        /*=========== 目录序列 end ============*/
        /*具体样品检测报告数据及不合格照片链接 start*************************************************/
            $template->cloneBlock('block',count($result),true,true); //复制等份的数据模板
            $tool_names = array_keys($result);   //获取所有样品名称
            $contents = array_values($result);   //获取所有样品内容
            for ($i=0; $i < count($tools); $i++) { 
                $tool_name = $tool_names[$i];
                $content = $contents[$i];
                $j = $i+1; //块元素中生产的index
                $values['tool_name#'.$j] = $tool_name; //赋值给所有块元素的tool_name
                // $content_num = count($content);
                // $template->cloneBlock('block_data#'.$j,$content_num,true,true); //复制检测数据模板
                $res1 = data_get($content,1,[]);
                $template->cloneBlock('block_data1#'.$j,($res1?1:0),true,true); //复制模板
                $res2 = data_get($content,2,[]);
                $template->cloneBlock('block_data2#'.$j,($res2?1:0),true,true); //复制模板
                //不合格照片
                $photos_count = data_get($res2,'count',0);
                $template->cloneBlock('block_photos#'.$j,$photos_count,true,true); //复制不合格照片模板
                foreach ($content as $res => $item) {
                    //整理不合格照片链接
                    $nonPhotos = data_get($item,'non_photos',[]);
                    if ($nonPhotos) {
                        for($photoI = 0; $photoI<$photos_count; $photoI++){
                            $nonPhoto = data_get($nonPhotos,$photoI,[]);
                            $photoJ = $photoI + 1;
                            foreach ($nonPhoto as $col => $val) {
                                $values["{$col}#{$j}#{$photoJ}"] = $val;
                            }
                        }
                        unset($item['non_photos']);
                    }
                    foreach ($item as $col => $val) {
                        $values["{$col}{$res}#{$j}#1"] = $val;
                    }
                }
            }
        /*具体样品检测报告数据及不合格照片链接 end*************************************************/
        //追加参数，pNo_report pNo_item 最好写在后面，不然会影响目录布局
        $values['pNo_report']  =  $pNo_report; 
        $values['pNo_item']  =  $pNo_item; 
        $values['totalPage'] = $pNo-1; //减去最后一个换行符引起的+1
        $values['number'] = array_sum(array_column($gys->toArray(),'count'));
        /*生产图片 start*/
            foreach ($values as $colK => $value) {
                try{
                    $colKs = explode('#',$colK);
                    $col = data_get($colKs,0,'');
                    if ($value && ($col == 'waiPic' || $col == 'detailPic')) {
                        $file = trim($value,'/');
                        if (file_exists($file)) {
                            $template->setImageValue($colK, ["path" => $file, "width" => 400, "height" => 300]);
                        }else{
                            $values[$colK] = '';
                        }
                    }
                }catch(\Exception $exception){
                    return $exception->getMessage();
                }
            }
        /*生产图片 end*/
        $template->setValues($values);
        
        return $this->saveDown($template,$data_batch);
    }
    //二维数据去重
    public function array_duplicate($arr){
        $tmp = array();
        $result = array();
        $result_arr = [];
        $i = 0;
        foreach($arr as $key => $val){
            $tmp[$key] = json_encode($val);
        }
        unset($val);
        $final = array_unique($tmp);
        foreach($final as $key => $val){
            $result[$key] = json_decode($val, true);
        }
        //序号重组
        foreach($result as $kk=>$vv){
            $result_arr[$i] = $vv;
            $i++;
        }

        return $result_arr;
    }


    //温湿度，大气压最大最小值
    public static function tempHumPressureSE($data) {
        if (is_object($data)) {
            $data = $data->toArray();
        }
        $temps = ary_filter(array_column($data,'temp'));
        $min = $temps ? min($temps) : '';
        $max = $temps ? max($temps) : '';
        $temp = ($min !== '' && $max !== '' && $min != $max)  ? "({$min}～{$max})" : ($max ? "{$max}" : '');
        $hums = ary_filter(array_column($data,'hum'));
        $min = $hums ? min($hums) : '';
        $max = $hums ? max($hums) : '';
        $hum = ($min !== '' && $max !== '' && $min != $max) ? "({$min}～{$max})" : ($max ? "{$max}" : '');
        $pressures = ary_filter(array_column($data,'pressure'));
        $min = $pressures ? min($pressures) :'';
        $max = $pressures ? max($pressures) : '';
        $pressure = ($min !== '' && $max !== '' && $min != $max) ? "({$min}～{$max})" : ($max ? "{$max}" : '');
        return [$temp, $hum, $pressure];
    }

    //获取指定字符串所占行数：一个英文或中文按照2个字符计算
    private function getStrRows($str,$perStrLen){
        $len = (strlen($str) + mb_strlen($str,'UTF-8'))/2;
        return ceil($len/$perStrLen);
    }

    /*
        4.检测仪器设备占用行数统计  
        $array 二维数组
        $per_row_limit：每个字段每行文字限制个数，它的key必须在$array元素的下标是存在的
        $page_limit = 【起始页最大占用行数，整页最大占用行数】
    */
    private function getRowLimit($array,$per_row_limit,$page_limit=[]){
        $rows = 0; //初始化,所有设备共计可以占用的行数
        foreach ($array as $item) {
            $rownum = 1;
            foreach ($item as $col=>$value) {
                $row_limit = data_get($per_row_limit,$col,'');
                if($row_limit){
                    $col_row = $this->getStrRows($value,$row_limit);
                    $rownum = $col_row > $rownum ?  $col_row : $rownum; //计算当前内容占用行数
                }
            }
            $rows += $rownum;
        }
        $pages = 1;
        $last_page_left_rows = data_get($page_limit,1,21);
        if ($page_limit) {
            list($p1Limit,$p2Limit) = $page_limit;
            $pages = $rows > $p1Limit ? ceil(($rows-$p1Limit)/$p2Limit)+1 : 1;
            $last_page_left_rows = $pages > 1 ? $p2Limit-($rows-$p1Limit)%$p2Limit : $p1Limit - $rows;
        }
        
        return [$rows,$pages,$last_page_left_rows];
    }

    private function NewgetBarCodes($contract_id){
        $selfcodearray = [];
        $self_no = DB::table('a_sample_info')->where('contract_id',$contract_id)->pluck('self_num')->toArray();
        sort($self_no);
        $selfcodearray = implode('、',$self_no);
        return $selfcodearray;
    }

    private function NewgetBarCodes2($gaiyao_id,$res){
        $selfcodearray = [];
        $self_no = DB::table('a_sample_info')->where('res',$res)->where('contract_gaiyao_id',$gaiyao_id[0])->pluck('self_num')->toArray();
        sort($self_no);
        $selfcodearray = implode('、',$self_no);

        return $selfcodearray;
    }

    private function getBarCodes($contract_id){
        $barcodeAry = [];
        $bcs = DB::table('a_contract_gaiyao')->where('contract_id',$contract_id)->pluck('bar_codes')->toArray();
        sort($bcs);
        $start = '';
        foreach ($bcs as $bcItem) {
            $nextBC = next($bcs);
            list($bc1,$bc2) = explode('～',$bcItem);
            if ($start === '') {
                $start = $bc1;
                $end = $bc2;
            }
            if($nextBC){
                list($bc1,$bc2) = explode('～',$nextBC);
                if($bc1 == ($end+1)){
                    $end = $bc2;
                }else{
                    $barcodeAry[] = "{$start}～{$end}";
                    $start = '';
                }
            }else{
                $barcodeAry[] = "{$start}～{$end}";
            }
        }
        $bar_code_str = '';
        foreach ($barcodeAry as $bar_code_item) {
            $bar_code_str .= "，{$bar_code_item}";
        }
        $bar_code_str = trim($bar_code_str,'，');
        return $bar_code_str;
    }

    private function getBarCodes2($bar_codes){
        sort($bar_codes); //升序排序
        $barcodeAry = [];
        $start = '';
        foreach ($bar_codes as $bc1) {
            $bc2 = next($bar_codes);
            if ($start === '') {
                $start = $bc1;
                $end = $bc2;
            }
            if($bc2){
                if($bc1 == ($end+1)){
                    $end = $bc2;
                }else{
                    $barcodeAry[] = "{$start}～{$end}";
                    $start = '';
                }
            }else{
                $barcodeAry[] = $end ? "{$start}～{$end}" : "{$start}～{$start}";
            }
        }
        $bar_code_str = '';
        foreach ($barcodeAry as $bar_code_item) {
            $bar_code_str .= "，{$bar_code_item}";
        }
        $bar_code_str = trim($bar_code_str,'，');
        return $bar_code_str;
    }

    //字符串转数组去重
    private function getUnique($source,$glue='，',$array = false){
        if (is_string($source)) {
            $source = explode($glue,$source);
        }
        $source = explode($glue,implode($glue, $source));
        if ($array) {
            return array_unique($source);
        }
        $source = implode($glue,array_unique($source));
        return $source;
    }

    private function getYaoqius2($itemV){
        $yaoqius = [];
        $where = [];
        foreach ($itemV as $item) {
            $condition = $item->std_id.';'.$item->tool_id.';'.$item->item_ids;
            if (in_array($condition,$where)) {
                continue;
            }
            $yaoqiu = DB::table('a_std_tool_item_rel')
                ->where(['std_id'=>$item->std_id,'tool_id'=>$item->tool_id])
                ->whereIn('testitem_id',explode(',',$item->item_ids))
                ->pluck('jishu_yaoqiu')->toArray();
            if($yaoqiu){
                foreach($yaoqiu as &$val){
                    $val = rtrim($val,'。');
                }
            }
            $yaoqius = array_merge($yaoqius,$yaoqiu);
        }
        $jishu_yaoqiu = implode('；',array_unique($yaoqius));
        return $jishu_yaoqiu;
    }

    //获取周期
    private function getCycle2($itemV){
        $cycles = [];
        $where = [];
        $itemDataCon = new ItemDataController();
        foreach ($itemV as $item) {
            $condition = $item->std_id.';'.$item->tool_id.';'.$item->vol_id.';'.$item->class_id;
            if (in_array($condition,$where)) {
                continue;
            }
            $cycle = $itemDataCon->get_cycle($item);
            $cycles[] = $cycle*12;
        }
        $cycles = array_unique($cycles);
        return implode('/',$cycles);
    }

    private function getEnv2($itemV){
        $env_data = [];
        foreach ($itemV as $item) {
            $itemData = DB::table('a_item_data')->select('temp','hum')->where('sample_info_id',$item->sample_info_id)->where('res','<',2)->where('item_id','!=',61)->get()->toArray();
            $env_data = array_merge($env_data, $itemData);
        }
        $se = ExportReportPublicController::tempHumPressureSE($env_data,false);
        return $se;

    }    

    private function getTestDataVals2($resV){
        // dd(11,$resV);
        $sample_info_ids = $resV['sample_info_ids'];
        $data = [];
        foreach ($sample_info_ids as $sample_info_id) {
            $data[] = DB::table('a_input_data as a')
                ->leftJoin('a_testdata_key as b','a.testdata_key_id','=','b.id')
                ->leftJoin('a_testitem as c','b.item_id','=','c.id')
                ->leftJoin('a_std_tool_item_rel as d','b.std_tool_item_rel_id','=','d.id')
                ->where([
                    ['a.sample_info_id', '=', $sample_info_id],
                    ['b.pos_start', '!=', ''], 
                ])
                ->select('a.sample_info_id','a.val','b.data_key','b.data_unit','b.pos_start','c.name as item_name')
                ->orderBy('d.sort','asc')
                ->orderBy('b.sort','asc')
                ->get();
        }
        $results = [];
        foreach ($data as $bar_code => $values) {
            foreach ($values as $key => $value) {
                $results[$value->item_name][$value->data_key][$value->data_unit][] = $value->val;
            }
        }
        $str = '';
        foreach ($results as $item_name => $values) {
            if($values){
                $str .= "<w:br/>{$item_name}：-";
                foreach ($values as $data_key => $data_key_v) {
                    if ($data_key_v) {
                        foreach ($data_key_v as $data_unit => $vals) {
                            if ($vals) {
                                $str = rtrim($str,'-');
                                $val1 = min($vals);
                                $val2 = max($vals);
                                if ($val1 == $val2) {
                                    $val = $val1;
                                }else{
                                    if($val1) {
                                        $val = "{$val1}-{$val2}";
                                    }else{
                                        $val = $val2;
                                    }
                                }
                                $str .= "{$data_key}:{$val}{$data_unit}；";
                                
                            }
                        }
                    }
                }
            }
        }
        return trim($str,'<w:br/>');
    }

    private function getRemark2($itemV){
        $str = '';
        foreach ($itemV as $item) {
            $remarks = DB::table('a_item_data')->where('sample_info_id',$item->sample_info_id)->pluck('remark');
            foreach ($remarks as $remark) {
                if ($remark && $remark !== '无') {
                    $str .= $remark.';';                     
                }
            }
        }
        return rtrim($str); 
    }

    private function getTestDataVals($std_id,$tool_id,$item_ids){
        $item_res = DB::table('a_std_tool_item_rel')->select('id', 'testitem_id', 'pos_start', 'pos_end','line_num')->where([['std_id', '=', $std_id], ['tool_id', '=', $tool_id]])->get();
        $val_testdata_str = '';
        if($item_res) {
            foreach ($item_res as $vvv) {
                //获取试验项目名称
                $testitem_name = DB::table('a_testitem')->where('id', $vvv->testitem_id)->pluck('name');
                $testitem_name = $testitem_name ? $testitem_name[0] : '';
                $key_data = DB::table('a_testdata_key')
                    ->where('std_tool_item_rel_id', $vvv->id)
                    ->where([['pos_start', '!=', ''], ['pos_end', '!=', '']])
                    ->get();
                if (json_decode(json_encode($key_data), TRUE)) {
                    $val_testdata_str .= $testitem_name;
                }
                $arr_item_id = explode(',', $item_ids); //字符串 --》数组
                $b = in_array($vvv->testitem_id, $arr_item_id);
                foreach ($key_data as $kdKey => $vvv2) {
                    if ($b) {
                        $val_testdata = DB::table('a_input_data')->where([['testdata_key_id', '=', $vvv2->id]])->value('val');
                        $val_testdata_str .= $vvv2->data_key . "：" . $val_testdata . $vvv2->data_unit . '；';
                    }
                }
                $val_testdata_str .= '<w:br/>';
            }
            $val_testdata_str = rtrim($val_testdata_str,'<w:br/>');
        }
        return $val_testdata_str;
    }

    private function getTestAfter($gyIds){
        if (!is_array($gyIds)) {
            $gyIds = explode(',',$gyIds);
        }
        $str = '';
        foreach ($gyIds as $gyId) {
            $sampleIds = DB::table('a_sample_info')->where('contract_gaiyao_id',$gyId)->pluck('id');
            foreach ($sampleIds as $sampleId) {
                $remarks = DB::table('a_item_data')->where('sample_info_id',$sampleId)->pluck('remark');
                foreach ($remarks as $remark) {
                    if ($remark && $remark !== '无') {
                        $str .= $remark.';';                     
                    }
                }
            }
        }
        return rtrim($str);
    }

    private function getUnSeason($hzUnTotal){
        $item_names = [];
        foreach ($hzUnTotal as $hzUnItem) {
            $item_name = DB::table('a_item_data as a')
                ->leftjoin('a_testitem as b','a.item_id','=','b.id')
                ->where('a.sample_info_id',$hzUnItem->id)
                ->where('a.res',0)
                ->pluck('b.name')->toArray();
            if ($item_name) {
                $item_names[] = $item_name;
            }
        }
        //$item_names = array_count_values($item_names);
        $unSeason = '';
        foreach($item_names as $key=>$val){
            foreach($val as $item=>$count){
                $unSeason .= "{$count}不合格".';';
            }
        }
        /*foreach ($item_names as $item => $count) {
            if (count($item_names) == 1) {
                $unSeason .= "{$item}不合格";
            }else{
                $unSeason .= "{$count}件{$item}不合格<w:br/>";
            }
        }*/
        $unSeason = rtrim($unSeason,';');
        return rtrim($unSeason,'<w:br/>') ?: '/';
    }

    private function getNonPhotos($itemV){
        $res = [];
        foreach ($itemV as $item) {
            $nonPhotos = explode(',',$item->non_photo);
            $res[] = [
                'bar_code'=>$item->self_num,
                'tool_name'=>$item->tool_name,
                'waiPic'=>data_get($nonPhotos,1,''),
                'detailPic'=>data_get($nonPhotos,0,''),
            ];
        }
        return $res; 
    }

    private function saveDown($templateProcessor,$data_batch){
        // dd($data_batch);
        $disk = $this->disk;
        $storeFile = $this->storeFile;
        // dd($storeFile);
        if($data_batch->status > 13){
            try{
                $disk->put($storeFile,''); //创建路径
                $templateProcessor->saveAs($disk->path($storeFile));
                return $disk->download($storeFile);
            }catch(Exception $e){
                $disk->delete($storeFile);
            }
        }
        $filename = iconv("utf-8","gb2312",'检测报告'.$data_batch->batchNum);
        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition:attachment;filename=".$filename.".docx");
        header('Cache-Control: max-age=0');
        $templateProcessor->saveAs("php://output");
        exit;
    }

}
